import { NextRequest, NextResponse } from 'next/server';
import { authMiddleware, TokenPayload } from '@/utils/auth';
import UserModel from '@/models/user';

export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }

    const decoded = authResult as TokenPayload;
    const userId = decoded.id;

    // 获取用户信息
    const user = await UserModel.findById(userId);
    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }

    // 检查用户是否为企业负责人
    if (!user.is_company_admin) {
      return NextResponse.json(
        { error: '您不是企业负责人，无法删除招聘信息' },
        { status: 403 }
      );
    }

    const jobId = params.id;
    if (!jobId || isNaN(Number(jobId))) {
      return NextResponse.json(
        { error: '无效的职位ID' },
        { status: 400 }
      );
    }

    // 检查职位是否存在且属于该用户的企业
    const [jobs] = await UserModel.query<any[]>(
      `SELECT jp.*, c.admin_user_id
       FROM job_positions jp
       LEFT JOIN companies c ON jp.company_id = c.id
       WHERE jp.id = ?`,
      [jobId]
    );

    if (!jobs || jobs.length === 0) {
      return NextResponse.json(
        { error: '职位不存在' },
        { status: 404 }
      );
    }

    const job = jobs[0];

    // 检查职位是否属于该用户的企业
    if (job.admin_user_id !== userId) {
      return NextResponse.json(
        { error: '您无权删除此招聘信息' },
        { status: 403 }
      );
    }

    // 删除职位前，获取相关简历数量
    const [resumeCount] = await UserModel.query<any[]>(
      `SELECT COUNT(*) as count FROM resume_submissions WHERE position_id = ?`,
      [jobId]
    );

    // 删除职位
    await UserModel.query(
      `DELETE FROM job_positions WHERE id = ?`,
      [jobId]
    );

    console.log(`删除职位 ID ${jobId} 成功，相关简历数量: ${resumeCount[0]?.count || 0}`);

    return NextResponse.json({
      message: '招聘信息已成功删除',
      job_id: jobId
    });
  } catch (error) {
    console.error('删除招聘信息错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后再试' },
      { status: 500 }
    );
  }
}
